//
//  UISegmentedControlViewController.swift
//  Example
//
//  Created by T AO on 2022/2/15.
//

import UIKit
import RxSwift
import RxCocoa

class UISegmentedControlViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        segmentedRx()
    }

}

// MARK: - UISegmentedControl

extension UISegmentedControlViewController {
    private func segmentedRx() {
        let segmented = UISegmentedControl(items: ["one", "two", "three"])
        segmented.frame = CGRect(x: 50, y: 200, width: 300, height: 50)
        view.addSubview(segmented)
        
        segmented.selectedSegmentIndex = 0
        
        segmented.rx.selectedSegmentIndex
            .asObservable()
            .subscribe(onNext: { print("当前项：\($0)") })
            .disposed(by: disposeBag)
        
        let imageView = UIImageView(frame: CGRect(x: 50, y: 300, width: 100, height: 100))
        view.addSubview(imageView)
        
        // 创建一个当前需要显示的图片的可观察序列
        let showImageObservable: Observable<UIImage> = segmented.rx.selectedSegmentIndex
            .asObservable()
            .map {
                let images = ["sun.max.fill", "moon.stars", "cloud.rain"]
                return UIImage(systemName: images[$0]) ?? UIImage()
            }
        
        showImageObservable
            .bind(to: imageView.rx.image)
            .disposed(by: disposeBag)
    }
}
